#import "ZScanController.h"
// 导入<AVFoundation/AVFoundation.h>框架
#import <AVFoundation/AVFoundation.h>

@interface ZScanController ()<AVCaptureMetadataOutputObjectsDelegate>
/** 捕捉会话 */
@property (nonatomic, weak) AVCaptureSession *session;
/** 预览图层 */
@property (nonatomic, weak) AVCaptureVideoPreviewLayer *layer;
@property (nonatomic,strong) CALayer *indicator;
@property (nonatomic,strong) NSTimer *timer;

@end

@implementation ZScanController
- (NSTimer *)timer {
    
    if (!_timer) {
        
        _timer = [NSTimer scheduledTimerWithTimeInterval:4.0 target:self selector:@selector(scanLineMove) userInfo:nil repeats:YES];
        
        [_timer fire];
    }
    return _timer;
}
- (CALayer *)indicator
{
    if (!_indicator) {
        CALayer * layer = [[CALayer alloc] init];
        
        layer.bounds = CGRectMake(0, 0, 250, 1);
        
        layer.backgroundColor = [UIColor greenColor].CGColor;
        
        //起点
        layer.position = CGPointMake(0, 0);
        
        //定位点
        layer.anchorPoint = CGPointMake(0, 0);
        
        _indicator = layer;
        
      
    }return _indicator;
}

- (void)scanLineMove {
    
    CABasicAnimation * animation = [[CABasicAnimation alloc] init];
    
    //告诉系统要执行什么样的动画
    animation.keyPath = @"position";
    
    //设置通过动画  layer从哪到哪
    animation.fromValue = [NSValue valueWithCGPoint:CGPointMake(0, 0)];
    
    animation.toValue = [NSValue valueWithCGPoint:CGPointMake(0, 250)];
    
    //动画时间
    animation.duration = 4.0;
    
    //设置动画执行完毕之后不删除动画
    animation.removedOnCompletion = NO;
    
    //设置保存动画的最新动态
    animation.fillMode = kCAFillModeForwards;
    
    //添加动画到layer
    [self.indicator addAnimation:animation forKey:nil];
}


- (void)setupNav{
    UIButton *btn = [[UIButton alloc]init];
    btn.frame = CGRectMake(Scare_Width(10), Scare_Width(25), 44, 44);
    [btn setImage:[[UIImage imageNamed:@"back_close"]imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:UIControlStateNormal];
    [btn setTintColor:COLOR_MIDDLE_GRAY];
    [btn addTarget:self action:@selector(gotoback) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    self.view.backgroundColor = [UIColor colorWithHexString:@"#eaeaea"];
    UILabel *lab = [[UILabel alloc]init];
    lab.frame = CGRectMake(100, Scare_Width(25), SCREEN_W - 200, Scare_Width(25));
    lab.font = H2;
    lab.textColor = COLOR_NAV_TITLE;
    lab.text =  Z_Location(@"scan");
    lab.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:lab];
    CGFloat height = 250;
    CGFloat width = 250;
    
    CGFloat x = (SCREEN_W - width) *0.5;
    CGFloat y = (SCREEN_H - height) *0.5;
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    view.layer.borderColor = [UIColor greenColor].CGColor;
    view.layer.borderWidth = 1;
    view.backgroundColor = [UIColor clearColor];
    [self.view addSubview:view];
    [view.layer addSublayer:self.indicator];
//    [self setAnimation]; .
    [self timer];
//    [self scanLineMove];
}
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 扫描二维码
    [self scanCIQRCode];
    [self setupNav];
}
- (void)gotoback{
    [self dismissViewControllerAnimated:YES completion:nil];
}
/**
 *  扫描二维码
 */
- (void)scanCIQRCode
{
    // 1. 创建捕捉会话
    AVCaptureSession *session = [[AVCaptureSession alloc] init];
    self.session = session;
    
    // 2. 添加输入设备(数据从摄像头输入)
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    [session addInput:input];
    
    // 3. 添加输出数据接口
    AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
    // 设置输出接口代理
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    [session addOutput:output];
    // 3.1 设置输入元数据的类型(类型是二维码数据)
    // 注意，这里必须设置在addOutput后面，否则会报错
    [output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];
    
    // 4.添加扫描图层
    AVCaptureVideoPreviewLayer *layer = [AVCaptureVideoPreviewLayer layerWithSession:session];

    layer.frame = self.view.bounds;
    [self.view.layer addSublayer:layer];
    self.layer = layer;
   
    // 5. 开始扫描
    [session startRunning];
}

//- (void)viewDidDisappear:(BOOL)animated
//{
//
//}
#pragma mark - <AVCaptureMetadataOutputObjectsDelegate>

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    if (metadataObjects.count) {// 扫描到了数据
        AVMetadataMachineReadableCodeObject *object = [metadataObjects lastObject];
        for (NSDictionary *dic in object.corners) {
            ZWLog(@"dic == %@",dic);
        }
        self.scanResult(object.stringValue);
        ZWLog(@" object %@",object.stringValue);
        // 停止扫描
        [self.session stopRunning];
        
        // 将预览图层移除
        [self.layer removeFromSuperlayer];
        [self dismissViewControllerAnimated:YES completion:nil];
    }else{
        NSLog(@"没有扫描到数据");
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

@end


